package com.eddie.juc.cf;

import lombok.SneakyThrows;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @author Eddie
 * @date 2022/08/17 11:20
 **/
public class FutureThreadPoolDemo {
    @SneakyThrows
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        //三个任务，目前开启多个线程来处理
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        FutureTask<String> futureTask1 = new FutureTask<>(() -> {
            TimeUnit.MILLISECONDS.sleep(500);
            return "task1 over";
        });
        threadPool.submit(futureTask1);

        FutureTask<String> futureTask2 = new FutureTask<>(() -> {
            TimeUnit.MILLISECONDS.sleep(300);
            return "task2 over";
        });
        threadPool.submit(futureTask2);

        System.out.println(futureTask1.get());
        System.out.println(futureTask2.get());

        TimeUnit.MILLISECONDS.sleep(300);
        long endTime = System.currentTimeMillis();
        //测试为818,不使用get获取结果时为310，如果全部在主线程main中设置时为1.2s左右
        System.out.println("-----costTime：" + (endTime - startTime) + "毫秒");
        threadPool.shutdown();
    }

    private static void m1() throws InterruptedException {
        //三个任务，目前只有一个线程Main来处理
        long startTime = System.currentTimeMillis();
        //暂停毫秒
        TimeUnit.MILLISECONDS.sleep(500);
        TimeUnit.MILLISECONDS.sleep(300);
        TimeUnit.MILLISECONDS.sleep(300);

        long endTime = System.currentTimeMillis();
        System.out.println("-----costTime：" + (endTime - startTime) + "毫秒");
        System.out.println(Thread.currentThread().getName() + " ----end");
    }
}
